package echo;
import java.nio.charset.StandardCharsets;

import org.apache.log4j.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * Handler implementation for the echo server.
 */
@Sharable
public class EchoServerHandler extends ChannelHandlerAdapter {
	
	private static Logger logger = Logger.getLogger(EchoServerHandler.class);  
	
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
    	
    	
    	
    	ByteBuf buf = (ByteBuf)msg;
    	
//		byte[] bytes = new byte[buf.readableBytes()];
//		buf.readBytes(bytes);
//		
//		System.out.println("server recv:" + new String(bytes));
//    	
//		buf.resetReaderIndex(); //reset reader
		
    	logger.info("server recv:" + buf.toString(StandardCharsets.UTF_8));
		
        ctx.write(msg);  //write to the context object causes the message to start from the next handler in the ChannelPipeline.
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}